<template>
  <div class="data-source-config">
    <el-form :model="configForm" label-width="100px">
      <el-form-item label="数据源">
        <el-select v-model="configForm.sourceId" @change="handleSourceChange">
          <el-option
            v-for="source in dataSources"
            :key="source.id"
            :label="source.name"
            :value="source.id"
          />
        </el-select>
      </el-form-item>

      <!-- 图表特定配置 -->
      <template v-if="configForm.sourceId">
        <!-- 表格配置 -->
        <template v-if="chartType === 'table'">
          <el-form-item label="显示字段">
            <el-select v-model="configForm.fields" multiple>
              <el-option
                v-for="field in sourceFields"
                :key="field.name"
                :label="field.label"
                :value="field.name"
              />
            </el-select>
          </el-form-item>
        </template>

        <!-- 图表配置 -->
        <template v-else>
          <el-form-item label="X轴字段" v-if="chartType !== 'pie'">
            <el-select v-model="configForm.xField">
              <el-option
                v-for="field in sourceFields"
                :key="field.name"
                :label="field.label"
                :value="field.name"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="chartType === 'pie' ? '值字段' : 'Y轴字段'">
            <el-select v-model="configForm.yField">
              <el-option
                v-for="field in numericFields"
                :key="field.name"
                :label="field.label"
                :value="field.name"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="分类字段" v-if="chartType === 'pie'">
            <el-select v-model="configForm.categoryField">
              <el-option
                v-for="field in sourceFields"
                :key="field.name"
                :label="field.label"
                :value="field.name"
              />
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="自动刷新">
          <el-switch v-model="configForm.autoRefresh" />
        </el-form-item>

        <el-form-item label="刷新间隔" v-if="configForm.autoRefresh">
          <el-input-number
            v-model="configForm.refreshInterval"
            :min="5"
            :max="3600"
            :step="5"
          />
          秒
        </el-form-item>
      </template>
    </el-form>

    <div class="form-actions">
      <el-button type="primary" @click="handleSubmit">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DataSourceConfig',
  props: {
    chartType: {
      type: String,
      required: true,
    },
    currentConfig: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      dataSources: [],
      sourceFields: [],
      configForm: {
        sourceId: '',
        fields: [],
        xField: '',
        yField: '',
        categoryField: '',
        autoRefresh: false,
        refreshInterval: 30,
      },
    }
  },
  computed: {
    numericFields() {
      return this.sourceFields.filter((field) =>
        ['number', 'integer', 'float'].includes(field.type)
      )
    },
  },
  created() {
    this.loadDataSources()
    // 如果有现有配置，加载它
    if (this.currentConfig.sourceId) {
      this.configForm = { ...this.currentConfig }
      this.handleSourceChange(this.currentConfig.sourceId)
    }
  },
  methods: {
    async loadDataSources() {
      try {
        // 这里替换为实际的API调用
        const response = await fetch('/api/dataSources')
        const data = await response.json()

        // 如果没有获取到数据源，使用默认数据源
        if (!data || data.length === 0) {
          this.dataSources = [
            {
              id: 'default-1',
              name: '销售数据',
              type: 'mock',
              fields: [
                { name: 'date', label: '日期', type: 'date' },
                { name: 'sales', label: '销售额', type: 'number' },
                { name: 'category', label: '品类', type: 'string' },
                { name: 'region', label: '地区', type: 'string' },
                { name: 'profit', label: '利润', type: 'number' },
              ],
            },
            {
              id: 'default-2',
              name: '访问统计',
              type: 'mock',
              fields: [
                { name: 'time', label: '时间', type: 'datetime' },
                { name: 'pv', label: '访问量', type: 'number' },
                { name: 'uv', label: '用户数', type: 'number' },
                { name: 'source', label: '来源', type: 'string' },
                { name: 'bounce', label: '跳出率', type: 'number' },
              ],
            },
          ]
        } else {
          this.dataSources = data
        }

        // 如果有选中的数据源，加载其字段
        if (this.configForm.sourceId) {
          this.handleSourceChange(this.configForm.sourceId)
        }
      } catch (error) {
        console.error('Failed to load data sources:', error)
        // 加载失败时也使用默认数据源
        this.dataSources = [
          {
            id: 'default-1',
            name: '销售数据',
            type: 'mock',
            fields: [
              { name: 'date', label: '日期', type: 'date' },
              { name: 'sales', label: '销售额', type: 'number' },
              { name: 'category', label: '品类', type: 'string' },
              { name: 'region', label: '地区', type: 'string' },
              { name: 'profit', label: '利润', type: 'number' },
            ],
          },
          {
            id: 'default-2',
            name: '访问统计',
            type: 'mock',
            fields: [
              { name: 'time', label: '时间', type: 'datetime' },
              { name: 'pv', label: '访问量', type: 'number' },
              { name: 'uv', label: '用户数', type: 'number' },
              { name: 'source', label: '来源', type: 'string' },
              { name: 'bounce', label: '跳出率', type: 'number' },
            ],
          },
        ]
        this.$message.warning('使用默认数据源')
      }
    },

    async handleSourceChange(sourceId) {
      try {
        // 先查找本地默认数据源
        const defaultSource = this.dataSources.find((s) => s.id === sourceId)
        if (defaultSource?.fields) {
          this.sourceFields = defaultSource.fields
          return
        }

        // 如果不是默认数据源，则调用API
        const response = await fetch(`/api/dataSources/${sourceId}/fields`)
        const fields = await response.json()
        if (fields && fields.length > 0) {
          this.sourceFields = fields
        } else {
          throw new Error('No fields returned')
        }
      } catch (error) {
        console.error('Failed to load fields:', error)
        // 加载失败时使用模拟数据
        this.sourceFields = [
          { name: 'date', label: '日期', type: 'date' },
          { name: 'value', label: '数值', type: 'number' },
          { name: 'category', label: '分类', type: 'string' },
          { name: 'name', label: '名称', type: 'string' },
        ]
        this.$message.warning('使用默认字段配置')
      }
    },

    handleSubmit() {
      this.$emit('submit', this.configForm)
    },

    handleCancel() {
      this.$emit('cancel')
    },
  },
}
</script>

<style scoped>
.data-source-config {
  padding: 20px;
}

.form-actions {
  text-align: right;
  margin-top: 20px;
}
</style> 